package cn.eleme.meal.utils;

import net.sf.json.JSONObject;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;

public class HttpUtil
{
    static int sum;
    
    public static String getCookies( List<String> cookies) {
         StringBuilder cookieBuilder = new StringBuilder();
        for (int i = 0; i < cookies.size(); ++i) {
            if (i != cookies.size() - 1) {
                cookieBuilder.append(cookies.get(i)).append("; ");
            }
            else {
                cookieBuilder.append(cookies.get(i));
            }
        }
        return cookieBuilder.toString();
    }
    
    public static ArrayList<String> addCookies( Header[] responseHeaders,  ArrayList<String> cookies) {
         ArrayList<String> responseCookies = new ArrayList<String>();
        for (int i = 0; i < responseHeaders.length; ++i) {
            if ("Set-Cookie".equals(responseHeaders[i].getName())) {
                 String cookieString = responseHeaders[i].getValue().split(";")[0];
                if (!cookies.contains(cookieString)) {
                    responseCookies.add(cookieString);
                }
            }
        }
        cookies.addAll(responseCookies);
        System.out.println("cookie 池cookie 数量：" + cookies.size());
        return responseCookies;
    }
    
    public static String getCookieByName( String cookieName,  List<String> cookies) {
        if (cookieName == null || "".equals(cookieName)) {
            return "";
        }
        for (int i = 0; i < cookies.size(); ++i) {
            if (cookies != null) {
                 String[] cookie = cookies.get(i).split(";");
                for (int j = 0; j < cookie.length; ++j) {
                    if (cookie[j].indexOf(cookieName) != -1) {
                        return cookie[j];
                    }
                }
            }
        }
        return "";
    }
    
    public static String doGet( String url) {
        try {
             HttpClient client = (HttpClient)new DefaultHttpClient();
             HttpGet request = new HttpGet(url);
             HttpResponse response = client.execute((HttpUriRequest)request);
            if (response.getStatusLine().getStatusCode() == 200) {
                 String strResult = EntityUtils.toString(response.getEntity());
                return strResult;
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static String doGet( String url,  Map<String, String> map,  Map<String, String> header) {
         CloseableHttpClient httpClient = HttpClients.createDefault();
        String entityStr = null;
        CloseableHttpResponse response = null;
        try {
             URIBuilder uriBuilder = new URIBuilder(url);
            if (map != null) {
                for ( Entry<String, String> entry : map.entrySet()) {
                    uriBuilder.addParameter((String)entry.getKey(), (String)entry.getValue());
                }
            }
             HttpGet httpGet = new HttpGet(uriBuilder.build());
             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(5000).build();
            httpGet.setConfig(requestConfig);
            if (header != null) {
                for ( Entry<String, String> entry2 : header.entrySet()) {
                    httpGet.addHeader((String)entry2.getKey(), (String)entry2.getValue());
                }
            }
            response = httpClient.execute((HttpUriRequest)httpGet);
             HttpEntity entity = response.getEntity();
            entityStr = EntityUtils.toString(entity, "utf-8");
            return entityStr;
        }
        catch (SocketTimeoutException e6) {
            System.err.println("网络不通或者网络慢");
        }
        catch (UnknownHostException e7) {
            System.err.println("不能识别host 请求头异常,不影响程序使用");
        }
        catch (ClientProtocolException e) {
            System.err.println("Http协议出现问题");
            e.printStackTrace();
        }
        catch (ParseException e2) {
            System.err.println("解析错误");
            e2.printStackTrace();
        }
        catch (URISyntaxException e3) {
            System.err.println("URI解析异常");
            e3.printStackTrace();
        }
        catch (IOException e4) {
            System.err.println("IO异常");
            e4.printStackTrace();
        }finally {

            if (response != null) {
                try {
                    response.close();
                    httpClient.close();
                }
                catch (IOException e5) {
                    System.err.println("释放连接出错");
                    e5.printStackTrace();
                }
            }
        }
        return entityStr;
    }
    
    public static String httpGet( String url,  Map<String, String> map,  Map<String, String> header) {
        String result = "";
         HttpClient httpClient = (HttpClient)HttpClients.createDefault();
        try {
             URIBuilder uriBuilder = new URIBuilder(url);
            if (map != null) {
                for ( Entry<String, String> entry : map.entrySet()) {
                    uriBuilder.addParameter((String)entry.getKey(), (String)entry.getValue());
                }
            }
             HttpGet httpGet = new HttpGet(uriBuilder.build());
             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(5000).build();
            httpGet.setConfig(requestConfig);
            if (header != null) {
                for ( Entry<String, String> entry2 : header.entrySet()) {
                    httpGet.addHeader((String)entry2.getKey(), (String)entry2.getValue());
                }
            }
             HttpResponse response = httpClient.execute((HttpUriRequest)httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity());
                return result;
            }
            return result;
        }
        catch (SocketTimeoutException e6) {
            System.err.println("网络不通或者网络慢");
            if (HttpUtil.sum < 5) {
                ++HttpUtil.sum;
                try {
                    Thread.sleep(3000L);
                }
                catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                 String result2 = httpGet(url, map, header);
                if (!StringUtils.isEmpty(result2) && result2.contains("wmOrderList")) {
                    result = result2;
                    HttpUtil.sum = 0;
                    return result2;
                }
            }
            if (!StringUtils.isEmpty(result) && result.contains("wmOrderList")) {
                HttpUtil.sum = 0;
                return result;
            }
            return result;
        }
        catch (UnknownHostException e7) {
            System.err.println("出现异常,偶尔出现不影响使用");
            if (!StringUtils.isEmpty(result) && result.contains("wmOrderList")) {
                HttpUtil.sum = 0;
                return result;
            }
            return result;
        }
        catch (ClientProtocolException e2) {
            System.err.println("Http协议出现问题");
            e2.printStackTrace();
            if (!StringUtils.isEmpty(result) && result.contains("wmOrderList")) {
                HttpUtil.sum = 0;
                return result;
            }
            return result;
        }
        catch (ParseException e3) {
            System.err.println("解析错误");
            e3.printStackTrace();
            if (!StringUtils.isEmpty(result) && result.contains("wmOrderList")) {
                HttpUtil.sum = 0;
                return result;
            }
            return result;
        }
        catch (URISyntaxException e4) {
            System.err.println("URI解析异常");
            e4.printStackTrace();
            if (!StringUtils.isEmpty(result) && result.contains("wmOrderList")) {
                HttpUtil.sum = 0;
                return result;
            }
            return result;
        }
        catch (IOException e5) {
            System.err.println("IO异常");
            e5.printStackTrace();
            if (!StringUtils.isEmpty(result) && result.contains("wmOrderList")) {
                HttpUtil.sum = 0;
                return result;
            }
            return result;
        }
        finally{
            if (!StringUtils.isEmpty(result) && result.contains("wmOrderList")) {
                HttpUtil.sum = 0;
                return result;
            }
        }
    }
    
    public static String doPost(String url, JSONObject param, Map<String, String> header) {
        InputStreamReader in = null;
        try {
             HttpClient client = wrapClient() ;// (HttpClient)new DefaultHttpClient();
             HttpPost post = new HttpPost();
            post.setURI(new URI(url));
            if (param != null) {
                 StringEntity se = new StringEntity(param.toString(), "utf-8");
                post.setEntity((HttpEntity)se);
            }
            if (header != null) {
                for ( Entry<String, String> entry : header.entrySet()) {
                    post.addHeader((String)entry.getKey(), (String)entry.getValue());
                }
            }
             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(5000).build();
            post.setConfig(requestConfig);
             HttpResponse response = client.execute((HttpUriRequest)post);
             int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                in = new InputStreamReader (response.getEntity().getContent());
                StringBuffer sb = new StringBuffer("");
                int line = 0;
                char[] bytes = new char[1024];
                String NL = System.getProperty("line.separator");
                while ((line = in.read(bytes)) > 0) {
                    sb.append(bytes);
                    bytes = new char[1024];
                }
                in.close();

                return sb.toString();
            }

            System.out.println("状态码：" + code);
            return null;
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String doPost( String url,  List<NameValuePair> param,  Map<String, String> header) {
        BufferedReader in = null;
        try {
            //  HttpClient client = (HttpClient)new DefaultHttpClient();
        	 HttpClient client = wrapClient();
             HttpPost post = new HttpPost();
            post.setURI(new URI(url));
            if (param != null) {
                post.setEntity((HttpEntity)new UrlEncodedFormEntity((List)param, "UTF-8"));
            }
            if (header != null) {
                for ( Entry<String, String> entry : header.entrySet()) {
                    post.addHeader((String)entry.getKey(), (String)entry.getValue());
                }
            }
             HttpResponse response = client.execute((HttpUriRequest)post);
             int code = response.getStatusLine().getStatusCode();
            if (code < 400) {
                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
                 StringBuffer sb = new StringBuffer("");
                String line = "";
                 String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(String.valueOf(line) + NL);
                }
                in.close();
				// System.out.print("出餐结果:" + sb.toString());
                return sb.toString();
            }
            System.out.println("状态码：" + code);
            return null;
        }
        catch (SocketTimeoutException e2) {
            System.err.println("网络不通或者网络慢");
            return null;
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    //绕过https证书
	public static HttpClient wrapClient() {
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {
				@Override
                public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
				@Override
                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
				}

				@Override
                public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
			CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).build();
			return httpclient;
		} catch (Exception e) {
			return HttpClients.createDefault();
		}
	}
    
    public static String doPost( String url,  String params) throws Exception {
         CloseableHttpClient httpclient = HttpClients.createDefault();
         HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
         String charSet = "UTF-8";
         StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity((HttpEntity)entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute((HttpUriRequest)httpPost);
             StatusLine status = response.getStatusLine();
             int state = status.getStatusCode();
            if (state == 200) {
                 HttpEntity responseEntity = response.getEntity();
                 String jsonString = EntityUtils.toString(responseEntity);
                return jsonString;
            }
            System.out.println("请求返回:" + state + "(" + url + ")");
        }finally {

            if (response != null) {
                try {
                    response.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (response != null) {
            try {
                response.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            httpclient.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
